import express from "express";
import proxy from "express-http-proxy";
import path from "path";
import { fileURLToPath } from "url";

function createServer(log) {
  const env = process.env.NODE_ENV;
  const app = express();
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
  const staticFilePath =
    env === "development"
      ? path.join(__dirname, "../../dist")
      : path.join(__dirname, "../../");

  app.use((req, res, next) => {
    log.info(`request from frontend: ${req.method} ${req.originalUrl}`);
    next();
  });
  app.use(express.static(staticFilePath));
  app.use("/server", proxy(process.env.VITE_SERVER_HOST));
  app.use("*", (req, res) => {
    res.sendFile(staticFilePath + "/index.html");
  });
  return { app };
}

export default { createServer };
